import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import type { ApiResponse } from '../api/types'

// 请求配置
const config: AxiosRequestConfig = {
  baseURL: process.env.NODE_ENV === 'production' 
    ? '/api' 
    : 'http://106.52.62.226:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
}

// 创建axios实例
const service: AxiosInstance = axios.create(config)

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 可以在这里添加token等认证信息
    // const token = uni.getStorageSync('token')
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`
    // }
    
    console.log('Request:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const { data } = response
    
    // 统一处理响应
    if (data.success) {
      return response
    } else {
      // 业务错误处理
      const errorMessage = data.message || '请求失败'
      uni.showToast({
        title: errorMessage,
        icon: 'error',
        duration: 2000
      })
      return Promise.reject(new Error(errorMessage))
    }
  },
  (error) => {
    console.error('Response Error:', error)
    
    let errorMessage = '网络错误'
    
    if (error.response) {
      // 服务器响应错误
      const { status, data } = error.response
      switch (status) {
        case 400:
          errorMessage = data?.message || '请求参数错误'
          break
        case 401:
          errorMessage = '未授权，请重新登录'
          // 可以在这里处理登录跳转
          break
        case 403:
          errorMessage = '拒绝访问'
          break
        case 404:
          errorMessage = '请求的资源不存在'
          break
        case 500:
          errorMessage = '服务器内部错误'
          break
        default:
          errorMessage = data?.message || `请求失败 (${status})`
      }
    } else if (error.request) {
      // 网络错误
      errorMessage = '网络连接失败，请检查网络设置'
    } else {
      // 其他错误
      errorMessage = error.message || '未知错误'
    }
    
    uni.showToast({
      title: errorMessage,
      icon: 'error',
      duration: 2000
    })
    
    return Promise.reject(error.response.data)
  }
)

// 封装请求方法
export const request = {
  get<T = any>(url: string, params?: any): Promise<ApiResponse<T>> {
    return service.get(url, { params }).then(response => response.data)
  },
  
  post<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return service.post(url, data).then(response => response.data)
  },
  
  put<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return service.put(url, data).then(response => response.data)
  },
  
  delete<T = any>(url: string, params?: any): Promise<ApiResponse<T>> {
    return service.delete(url, { params }).then(response => response.data)
  },
  
  patch<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return service.patch(url, data).then(response => response.data)
  }
}

export default request